/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.consumer.modular.structure.group.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.consumer.core.enums.ConsumerBuildInEnum;
import vip.xiaonuo.consumer.modular.structure.group.param.*;
import vip.xiaonuo.consumer.modular.structure.org.entity.ConsumerOrg;
import vip.xiaonuo.consumer.modular.structure.org.service.ConsumerOrgService;
import vip.xiaonuo.consumer.modular.structure.user.entity.ConsumerUser;
import vip.xiaonuo.consumer.modular.structure.user.service.ConsumerUserService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.consumer.modular.structure.group.entity.ConsumerGroup;
import vip.xiaonuo.consumer.modular.structure.group.mapper.ConsumerGroupMapper;
import vip.xiaonuo.consumer.modular.structure.group.service.ConsumerGroupService;
import vip.xiaonuo.sys.api.SysGroupApi;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户组Service接口实现类
 *
 * @author yubaoshan
 * @date  2024/12/24 03:33
 **/
@Service
public class ConsumerGroupServiceImpl extends ServiceImpl<ConsumerGroupMapper, ConsumerGroup> implements ConsumerGroupService {

    @Resource
    private SysGroupApi sysGroupApi;

    @Resource
    private ConsumerUserService consumerUserService;

    @Resource
    private ConsumerOrgService consumerOrgService;

    @Override
    public Page<ConsumerGroup> page(ConsumerGroupPageParam consumerGroupPageParam) {
        QueryWrapper<ConsumerGroup> queryWrapper = new QueryWrapper<ConsumerGroup>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(consumerGroupPageParam.getName())) {
            queryWrapper.lambda().like(ConsumerGroup::getName, consumerGroupPageParam.getName());
        }
        //数据归属
        queryWrapper.lambda().eq(ConsumerGroup::getCompanyId,StpLoginUserUtil.getLoginUser().getCompanyId());
        if(ObjectUtil.isAllNotEmpty(consumerGroupPageParam.getSortField(), consumerGroupPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(consumerGroupPageParam.getSortOrder());
            queryWrapper.orderBy(true, consumerGroupPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(consumerGroupPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(ConsumerGroup::getSortCode);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(ConsumerGroupAddParam consumerGroupAddParam) {
        ConsumerGroup consumerGroup = BeanUtil.toBean(consumerGroupAddParam, ConsumerGroup.class);
        //数据归属
        consumerGroup.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
        this.save(consumerGroup);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(ConsumerGroupEditParam consumerGroupEditParam) {
        ConsumerGroup consumerGroup = this.queryEntity(consumerGroupEditParam.getId());
        BeanUtil.copyProperties(consumerGroupEditParam, consumerGroup);
        this.updateById(consumerGroup);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<ConsumerGroupIdParam> consumerGroupIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(consumerGroupIdParamList, ConsumerGroupIdParam::getId));
    }

    @Override
    public ConsumerGroup detail(ConsumerGroupIdParam consumerGroupIdParam) {
        return this.queryEntity(consumerGroupIdParam.getId());
    }

    @Override
    public ConsumerGroup queryEntity(String id) {
        ConsumerGroup consumerGroup = this.getById(id);
        if(ObjectUtil.isEmpty(consumerGroup)) {
            throw new CommonException("用户组不存在，id值为：{}", id);
        }
        return consumerGroup;
    }

    @Override
    public List<String> ownUser(ConsumerGroupIdParam sysGroupIdParam) {
        return sysGroupApi.ownUser(sysGroupIdParam.getId());
    }

    @Override
    public List<Tree<String>> orgTreeSelector() {
        LambdaQueryWrapper<ConsumerOrg> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {
            loginUserDataScope.addAll(dataScope.getDataScope());
        }));
        // 定义机构集合
        Set<ConsumerOrg> consumerOrgSet = CollectionUtil.newHashSet();
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            // 获取所有机构
            List<ConsumerOrg> allOrgList = consumerOrgService.list();
            loginUserDataScope.forEach(orgId -> consumerOrgSet.addAll(consumerOrgService.getParentListById(allOrgList, orgId, true)));
            List<String> loginUserDataScopeFullList = consumerOrgSet.stream().map(ConsumerOrg::getId).collect(Collectors.toList());
            lambdaQueryWrapper.in(ConsumerOrg::getId, loginUserDataScopeFullList);
        } else {
            return CollectionUtil.newArrayList();
        }
        lambdaQueryWrapper.orderByAsc(ConsumerOrg::getSortCode);
        List<ConsumerOrg> consumerOrgList = consumerOrgService.list(lambdaQueryWrapper);
        List<TreeNode<String>> treeNodeList = consumerOrgList.stream().map(consumerOrg ->
                        new TreeNode<>(consumerOrg.getId(), consumerOrg.getParentId(), consumerOrg.getName(), consumerOrg.getSortCode()))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Override
    public Page<ConsumerUser> userSelector(ConsumerGroupSelectorUserParam consumerGroupSelectorUserParam) {
        LambdaQueryWrapper<ConsumerUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<String> loginUserDataScope = new ArrayList<>();
        StpLoginUserUtil.getLoginUser().getDataScopeList().stream().forEach((dataScope -> {
            loginUserDataScope.addAll(dataScope.getDataScope());
        }));
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            lambdaQueryWrapper.in(ConsumerUser::getOrgId, loginUserDataScope);
        } else {
            return new Page<>();
        }
        // 只查询部分字段
        lambdaQueryWrapper.select(ConsumerUser::getId, ConsumerUser::getAvatar, ConsumerUser::getOrgId, ConsumerUser::getPositionId, ConsumerUser::getAccount,
                ConsumerUser::getName, ConsumerUser::getSortCode, ConsumerUser::getGender, ConsumerUser::getEntryDate);
        if (ObjectUtil.isNotEmpty(consumerGroupSelectorUserParam.getOrgId())) {
            // 如果机构id不为空，则查询该机构及其子机构下的所有人
            List<String> childOrgIdList = CollStreamUtil.toList(consumerOrgService.getChildListById(consumerOrgService
                    .getAllOrgList(StpLoginUserUtil.getLoginUser().getCompanyId()), consumerGroupSelectorUserParam.getOrgId(), true), ConsumerOrg::getId);
            if (ObjectUtil.isNotEmpty(childOrgIdList)) {
                lambdaQueryWrapper.in(ConsumerUser::getOrgId, childOrgIdList);
            } else {
                return new Page<>();
            }
        }
        // 排除超管
        lambdaQueryWrapper.ne(ConsumerUser::getAccount, ConsumerBuildInEnum.BUILD_IN_USER_ACCOUNT.getValue());
        //需要排除自己
        lambdaQueryWrapper.ne(ConsumerUser::getId, StpLoginUserUtil.getLoginUser().getId());
        if (ObjectUtil.isNotEmpty(consumerGroupSelectorUserParam.getSearchKey())) {
            lambdaQueryWrapper.like(ConsumerUser::getName, consumerGroupSelectorUserParam.getSearchKey());
        }
        lambdaQueryWrapper.orderByAsc(ConsumerUser::getSortCode);
        return consumerUserService.page(CommonPageRequest.defaultPage(), lambdaQueryWrapper);
    }

    @Override
    public void grantUser(ConsumerGroupGrantUserParam consumerGroupGrantUserParam) {
        sysGroupApi.grantUser(consumerGroupGrantUserParam.getId(), consumerGroupGrantUserParam.getGrantInfoList());
    }
}
